<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordsQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!--
 children: null
department: null
dirPath: "/1"
id: 1
manager: null
manager_id: 324
name: "部门1"
parent_id: null
sn: "dept1"
state: 1
    -->
    <el-table
        :data="departments"
        highlight-current-row
        v-loading="listLoading"
        @selection-change="selsChange"
        style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门领导" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>
      <el-table-column label="状态" width="150">
        <template scope="scope">
          <el-span v-if="scope.row.state==1" style="color: green" size="small" >启用</el-span>
          <el-span v-else-if="scope.row.state==0" style="color: red" size="small" >禁用</el-span>
          <!-- <el-span v-elsef style="color: gray" size="small" >其他</el-span>-->
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" v-perm="'department:save'" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger"  v-perm="'department:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" v-perm="'department:delete'"  :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="5"
          :current-page="localPage"
          :total="totals"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="部门经理" prop="manager_id">
          <el-select v-model="editForm.manager_id" placeholder="请选择">
            <el-option
                v-for="item in managers"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级部门" prop="parent_id">
          <el-cascader v-model="editForm.parent_id"
                       :options="deptTree"
                       :props="{
                  checkStrictly: true ,
                  label:'name',
                  value:'id',
                }"
                       clearable></el-cascader>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>


export default {
  data() {
    return {
      filters: {
        name: ''
      },
      deptTree:[],
      departments: [],
      title:'',
      totals: 0,
      localPage: 1,
      pageSize: 5,
      listLoading: false,
      sels: [],//列表选中列

      managers: [],

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      editForm: {
        id: null,
        name: null,
        sn:null,
        state:1,
        manager_id:null,
        parent_id:null,
      },

      /*addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //新增界面数据
      addForm: {
        name: '',
        sex: -1,
        age: 0,
        birth: '',
        addr: ''
      }*/

    }
  },
  methods: {

    getDeptTree(){
      this.$http.get("/department/deptTree")
          .then(res=>{
            this.deptTree = res.data;
          }).catch(res=>{
        this.$message.error("系统繁忙")
      })
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    handleCurrentChange(currentPage) {
      this.localPage = currentPage;
      this.getDepartments();
    },
    keywordsQuery(){
      this.localPage=1;
      this.getDepartments()
    },
    //获取用户列表
    getDepartments() {
      let para = {
        localPage: this.localPage,
        pageSize: this.pageSize,
        keywords: this.filters.name
      };
      this.listLoading = true;
      //NProgress.start();
      this.$http.post("/department",para)
          .then(result => {
            this.listLoading = false;
            this.departments = result.data.data;
            this.totals = result.data.totals;
          }) .catch(result=>{
        this.$message.error("系统繁忙")
      })
    },
    getManagers() {
      this.listLoading = true;
      //NProgress.start();
      this.$http.get("/employee")
          .then(result => {
            //关闭忙灯框
            this.listLoading = false;
            this.managers = result.data;
          }) .catch(result=>{
        this.$message.error("系统繁忙")
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        //let para = row.id ;
        this.$http.delete("/department/"+row.id)
            .then(result=>{
              //关闭忙灯框
              this.listLoading = false;
              if(result.data.success){
                this.$message.success("删除成功")
                //刷新
                this.getDepartments()
              }else{
                this.$message.error(result.data.msg)
              }
            }).catch(() => {
          this.$message.error("系统繁忙,请稍后再试")
        })
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title="编辑"
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
      this.getManagers();
      this.getDeptTree();
      /*this.editForm={
            id: null,
            name: null,
            sn:null,
            state:1,
            manager_id:null,
            parent_id:null,
      }*/
    },
    //显示新增界面
    handleAdd: function () {
      this.title="新增"
      this.editFormVisible = true;
      this.editForm = {
        id: null,
        name: null,
        sn:null,
        state:1,
        manager_id:null,
        parent_id:null,
      };
      this.getManagers();
      this.getDeptTree();
    },

    //新增
    editSubmit: function () {

      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            this.$http.put("/department",para)
                .then(res=>{
                  //关闭模态框
                  this.editFormVisible = false;
                  //关闭忙灯框
                  this.editLoading = false;
                  if(res.data.success){
                    this.$message.success("新增成功")
                  }else{
                    this.$message.error(res.data.msg)
                  }
                  this.localPage=1;
                  this.getDepartments()
                })
            /*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
            addDepartment(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getDepartments();
            });*/
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //开启忙灯框
        this.listLoading = true;
        //NProgress.start();
        let para = { ids: ids };
        this.$http.patch("/department",ids)
            .then(res=>{
              this.listLoading = false;
              if (res.data.success){
                this.$message.success("删除成功")
                this.getDepartments()
              }else{
                this.$message.error(result.data.msg)
              }
            })
        /*batchRemoveDepartment(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartments();
        });*/
      }).catch(() => {
        this.$message.error("系统繁忙,请稍后再试")
      });
    }
  },
  mounted() {
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>